<template>
  <div class="category-container">
    <div class="category-header">
      <div class="header-content">
        <h2>{{ categoryInfo.label }}</h2>
        <p class="description">{{ categoryInfo.description }}</p>
      </div>
      <el-select v-model="sortBy" class="sort-select" @change="fetchVideos(true)">
        <el-option label="最新发布" value="latest" />
        <el-option label="最多观看" value="popular" />
        <el-option label="最受欢迎" value="trending" />
      </el-select>
    </div>

    <div class="filter-section">
      <el-select
        v-model="selectedTags"
        multiple
        collapse-tags
        collapse-tags-tooltip
        class="tag-select"
        placeholder="选择标签筛选"
        @change="handleTagsChange"
      >
        <el-option
          v-for="tag in categoryInfo.tags"
          :key="tag"
          :label="tag"
          :value="tag"
        />
      </el-select>

      <el-select v-model="timeRange" class="time-select" @change="fetchVideos(true)">
        <el-option label="全部时间" value="all" />
        <el-option label="今天" value="today" />
        <el-option label="本周" value="week" />
        <el-option label="本月" value="month" />
        <el-option label="今年" value="year" />
      </el-select>
    </div>

    <div class="video-content" v-loading="loading">
      <div v-if="videos.length === 0" class="empty-state">
        <el-empty :description="`暂无${categoryInfo.label}分类的视频`" />
      </div>

      <div v-else class="video-grid">
        <div v-for="video in videos" :key="video._id" class="video-card" @click="goToVideo(video._id)">
          <div class="thumbnail">
            <img :src="video.thumbnail" :alt="video.title">
            <span class="duration">{{ formatDuration(video.duration) }}</span>
            <div class="views-badge">
              <el-icon><View /></el-icon>
              {{ formatViews(video.views) }}
            </div>
          </div>
          <div class="video-info">
            <div class="channel-avatar">
              <!-- 修改：仅在频道有头像时显示头像 -->
              <el-avatar v-if="video.channel?.avatar" :size="36" :src="video.channel.avatar">
              </el-avatar>
              <!-- 可以选择添加一个占位符或图标 -->
              <!-- <el-avatar v-else :size="36"><User /></el-avatar> -->
            </div>
            <div class="video-details">
              <h3 class="title">{{ video.title }}</h3>
              <!-- 添加 v-if 判断 channel 是否存在 -->
              <div v-if="video.channel" class="channel-name">{{ video.channel.name }}</div>
              <div v-else class="channel-name">未知频道</div>
              <div class="stats">
                <span>{{ formatViews(video.views) }}次观看</span>
                <span class="dot">•</span>
                <span>{{ formatDate(video.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="load-more" v-if="hasMore && !loading">
        <el-button :loading="loadingMore" @click="loadMore">加载更多</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View } from '@element-plus/icons-vue'
import axios from 'axios' // 导入 axios

const router = useRouter()
const route = useRoute()

// 状态变量
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const sortBy = ref('latest')
const timeRange = ref('all')
const selectedTags = ref([])

// 视频列表
const videos = ref([])

// 分类信息
const categories = {
  entertainment: {
    label: '娱乐',
    description: '发现有趣的娱乐视频，包括综艺、搞笑、生活趣事等内容。',
    tags: ['搞笑', '综艺', 'vlog', '明星', '娱乐新闻']
  },
  music: {
    label: '音乐',
    description: '探索音乐世界，包括MV、现场表演、音乐教学等内容。',
    tags: ['流行音乐', '摇滚', '民谣', '说唱', '古典音乐', '演唱会']
  },
  // games: { // 旧 key
  gaming: { // 修正 key
    label: '游戏',
    description: '游戏视频内容，包括实况、攻略、解说等。',
    tags: ['实况', '攻略', '解说', '电子竞技', '手游', '主机游戏']
  },
  education: {
    label: '教育',
    description: '学习各类知识，包括课程、讲座、教程等内容。',
    tags: ['课程', '讲座', '教程', '考试', '语言学习', '职业技能']
  },
  tech: {
    label: '科技',
    description: '了解最新科技动态，包括数码、编程、科学等内容。',
    tags: ['数码', '编程', '科学', '人工智能', '科技新闻', '评测']
  },
  // life: { // 旧 key
  lifestyle: { // 修正 key
    label: '生活',
    description: '分享生活点滴，包括美食、旅游、时尚等内容。',
    tags: ['美食', '旅游', '时尚', '健康', '家居', '宠物']
  },
  // --- 补全缺失的分类 --- 
  movies: {
    label: '电影',
    description: '电影预告、影评、解析等相关内容。',
    tags: ['预告片', '影评', '电影推荐', '幕后花絮', '经典电影']
  },
  anime: {
    label: '动漫',
    description: '动画、漫画、二次元相关内容。',
    tags: ['新番', '漫评', 'AMV', 'MAD', '手办', 'Cosplay']
  },
  sports: {
    label: '体育',
    description: '体育赛事、健身、运动教学等内容。',
    tags: ['篮球', '足球', '健身', '跑步', '赛事集锦', '运动教学']
  },
  comedy: {
    label: '搞笑',
    description: '轻松幽默的搞笑视频。',
    tags: ['段子', '恶搞', '沙雕', '情景喜剧', '相声小品']
  },
  other: {
    label: '其他',
    description: '无法归类的其他视频内容。',
    tags: []
  }
 
}

// 获取当前分类信息
const categoryInfo = computed(() => {
  const categoryName = route.params.categoryName // 使用新的参数名

  // const correctedCategoryName = categoryName === 'games' ? 'gaming' : categoryName === 'life' ? 'lifestyle' : categoryName; // 不再需要修正逻辑
  // return categories[correctedCategoryName] || { // 使用修正后的 key
  return categories[categoryName] || { // 直接使用路由参数作为 key
    label: categoryName || '未知分类', // 如果找不到，显示参数名或未知
    description: '该分类不存在或信息未配置',
    tags: []
  }
})

// 获取视频列表
const fetchVideos = async (reset = true) => {
  if (reset) {
    loading.value = true
    videos.value = []
    currentPage.value = 1 // 重置页码
    hasMore.value = true // 重置是否有更多
  } else {
    loadingMore.value = true
  }

  if (!hasMore.value) {
    loadingMore.value = false;
    return; // 如果没有更多了，直接返回
  }

  try {
    const params = {
      page: currentPage.value,
      limit: videosPerPage.value,
      sort: sortBy.value,
      time: timeRange.value,
      // tags: selectedTags.value.join(',') // 旧逻辑：总是发送 tags
    }
    // 仅当 selectedTags 不为空时才添加 tags 参数
    if (selectedTags.value.length > 0) {
      params.tags = selectedTags.value.join(',');
    }
 
    const categoryLabel = categoryInfo.value.label;
    if (!categoryLabel || categoryLabel === '未知分类') {
      ElMessage.error('无法获取有效的分类信息');
      loading.value = false;
      loadingMore.value = false;
      return;
    }
    const response = await axios.get(`/api/videos/category/${categoryLabel}`, { params })
    const data = response.data

    if (reset) {
      videos.value = data.videos
    } else {
      videos.value.push(...data.videos)
    }

    hasMore.value = data.currentPage < data.totalPages
    currentPage.value++ // 准备加载下一页

  } catch (error) {
    console.error('获取分类视频失败:', error)
    // 打印更详细的错误信息
    if (error.response) {
      console.error('后端响应错误:', error.response.data);
      ElMessage.error(`获取分类视频失败: ${error.response.data.error || error.response.statusText}`);
    } else if (error.request) {
      console.error('请求已发出但无响应:', error.request);
      ElMessage.error('获取分类视频失败: 服务器无响应');
    } else {
      console.error('请求设置错误:', error.message);
      ElMessage.error(`获取分类视频失败: ${error.message}`);
    }
    // ElMessage.error(error.response?.data?.error || '获取分类视频失败') // 旧的错误提示
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多视频
const loadMore = () => {
  if (!loadingMore.value && hasMore.value) {
    fetchVideos(false)
  }
}

// 标签变化处理
const handleTagsChange = () => {
  fetchVideos(true)
}

// 格式化函数 (假设已在 utils/formatters 中定义)
import { formatDuration, formatViews, formatDate } from '@/utils/formatters'

// 导航到视频详情页
const goToVideo = (videoId) => {
  router.push({ name: 'VideoDetail', params: { id: videoId } })
}

// 分页相关
const currentPage = ref(1)
const videosPerPage = ref(12) // 每页加载的视频数量

// 监听路由参数变化
// watch(() => route.params.id, (newId, oldId) => { // 旧的监听
watch(() => route.params.categoryName, (newCategoryName, oldCategoryName) => { // 监听新的参数名
  // if (newId && newId !== oldId) { // 旧的判断
  if (newCategoryName && newCategoryName !== oldCategoryName) { // 使用新的参数名判断
    // 重置筛选条件和分页
    sortBy.value = 'latest'
    timeRange.value = 'all'
    selectedTags.value = []
    fetchVideos(true) // 重新获取视频
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchVideos(true)
})
</script>

<style scoped>
.category-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
}

.description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.sort-select {
  width: 120px;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.tag-select {
  flex: 1;
}

.time-select {
  width: 120px;
}

.video-content {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.video-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-2px);
}

.thumbnail {
  position: relative;
  aspect-ratio: 16/9;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 12px;
}

.views-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.video-info {
  display: flex;
  gap: 12px;
}

.channel-avatar {
  flex-shrink: 0;
}

.video-details {
  flex: 1;
  min-width: 0;
}

.title {
  margin: 0 0 8px 0;
  font-size: 14px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.channel-name {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
}

.stats {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.dot {
  margin: 0 4px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .category-header {
    flex-direction: column;
    gap: 16px;
  }

  .sort-select {
    width: 100%;
  }

  .filter-section {
    flex-direction: column;
  }

  .time-select {
    width: 100%;
  }

  .video-grid {
    grid-template-columns: 1fr;
  }
}
</style>